var PORT=8080;
var http=require('http');
var qs=require('qs');
var crypto=require('crypto');
var url=require('url');
var TOKEN="ningtowen";

function checkSignature(params,token){
	var key=[token,params.timestamp,params.nonce].sort().join('');
	var sha1=crypto.createHash('sha1');
	sha1.update(key);
	return sha1.digest('hex')==params.signature;
}

var server=http.createServer(function(request,response){
	var query=url.parse(request.url).query;
	var params=qs.parse(query);

	console.log(params);
	console.log("token:",TOKEN);

	if(!checkSignature(params,TOKEN)){
		response.end('signature fail');
	}

	if(request.method=="GET"){
		response.end(params.echostr);
	}else{
		var postdata='';
		request.addListener("data",function(postchunk){
			postdata=postdata+postchunk;
		});
		request.addListener("end",function(){
			console.log(postdata);
			response.end("success");
		});
	}
});

server.listen(process.env.VCAP_APP_PORT||PORT,function(){
	console.log('Server runing at port:'+(process.env.VCAP_APP_PORT||PORT));
})